package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断是否是登录请求，是登录则放行
        //1.1 获取请求路径
        String path = request.getRequestURI();
        log.info("请求路径： {}", path);
        //1.2 判断请求路径是否以/login结尾,是则放行 return true
        if(path.endsWith("/login")){
            return true;
        }
        //2.如果不是登录，则校验token有效性,有效就放行，无效则拒绝401
        //2.1 获取请求头中的token
        String token = request.getHeader("Token");
        //2.2 校验token是否有值，有值则校验
        if(StringUtils.hasText(token)) {
            //2.3 解析token
            try {
                Claims claims = JwtUtils.parseJWT(token);
                log.info("token内容：{}", claims);
                //2.4 如果不报错，解析成员，放行return true
                return true;
            } catch (Exception e) {
                log.error("token校验失败.", e);
            }
        }
        //全部拒绝，设置状态码为401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        //return true放行，false不放行
        return false;
    }

}
